# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.channel.pay import check_channel_order
from common.order.db import get_pay, add_pay_success
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.ip_address import check_valid_ip_address

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '10010': {
        'API_KEY': 'b3ac4588f0ac5bba91514de9d5ba4cb4',
    },
    # 测试环境
    # 'gateway': 'http://test9.nwj888.net/pay/api_pay',
    # 'query_gateway': 'http://test9.nwj888.net/pay/orderquery'
    # 正式环境
    'gateway': 'http://zcpay.nwj888.net/pay/api_pay',
    'query_gateway': 'http://zcpay.nwj888.net/pay/orderquery'
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway():
    return APP_CONF['gateway']


def _get_query_gateway():
    return APP_CONF['query_gateway']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf-8'))
    sign = m.hexdigest()
    return sign


def generate_verify_sign(parameter, key):
    s = ''
    for k, v in parameter.items():
        if v == '':
            continue
        s += '%s=%s&' % (k, v)
    s += '%s' % key
    return _gen_sign(s)


def _build_form(params, gateway):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + gateway + "' method='post'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>doc" \
            "ument.forms['submit'].submit();</script>"
    return html


def create_charge(pay, pay_amount, info):
    app_id = info['app_id']
    service = info.get('service')
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('version', '1.0'),  # 版本号
        ('mchid', str(app_id)),  # 商户号
        ('out_trade_no', str(pay.id)),  # 商户付款单号
        ('amount', '%.2f' % pay_amount),  # 交易金额 元
        ('channel', service),  # 交易种类
        ('notify_url', '{}/pay/api/{}/zhongchengpay/{}'.format(
            settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('return_url', '{}/pay/api/{}/zhongchengpay/'.format(
            settings.NOTIFY_PREFIX, settings.RETURN_PATH)),
    ))
    parameter_dict['sign'] = generate_verify_sign(parameter_dict, api_key)
    _LOGGER.info("zhongchengpay create date: %s, order_id is: %s", json.dumps(parameter_dict),
                 parameter_dict['out_trade_no'])
    html_text = _build_form(parameter_dict, _get_gateway())
    cache_id = redis_cache.save_html(pay.id, html_text)
    url = settings.PAY_CACHE_URL + cache_id
    return {'charge_info': url}


def verify_sign(params, key):
    st = 'mchid=%s&status=%s&trade_no=%s&out_trade_no=%s&amount=%s&%s' % (
        params['mchid'], params['status'], params['trade_no'],
        params['out_trade_no'], params['amount'], key
    )
    return _gen_sign(st)


def verify_notify_sign(params, key):
    sign = params.pop('sign')
    calculated_sign = verify_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("zhongchengpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


# success异步回调
def check_notify_sign(request, app_id):
    _LOGGER.info("zhongchengpay notify body: %s", request.body)
    data = dict(request.POST.iteritems())
    _LOGGER.info("zhongchengpay notify data: %s, order_id is: %s", data, data['out_trade_no'])
    verify_notify_sign(data, _get_api_key(app_id))
    pay_id = data['out_trade_no']
    check_valid_ip_address(str(request.META['REMOTE_ADDR']), pay_id)
    if not pay_id:
        _LOGGER.error("zhongchengpay fatal error, pay object not exists, data: %s" % data)
        raise ParamError('zhongchengpay event does not contain valid pay ID')
    pay = get_pay(pay_id)
    if not pay:
        raise ParamError('zhongchengpay pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('zhongchengpay pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = data['status']
    trade_no = data['out_trade_no']
    total_fee = float(data['amount'])
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee,
    }

    if trade_status == 'SUCCESS':
        check_channel_order(pay_id, total_fee, app_id)
        _LOGGER.info('zhongchengpay check order success, user_id:%s pay_id:%s' % (mch_id, pay_id))
        add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('version', '1.0'),  # 版本号
        ('mchid', str(app_id)),  # 商户号
        ('out_trade_no', str(pay_id)),  # 商户付款单号
    ))
    parameter_dict['sign'] = generate_verify_sign(parameter_dict, api_key)
    _LOGGER.info('zhongchengpay query data %s, order_id is: %s', json.dumps(parameter_dict),
                 parameter_dict['out_trade_no'])
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_query_gateway(), data=parameter_dict, headers=headers, timeout=5)
    data = json.loads(response.text)
    _LOGGER.info('zhongchengpay query rsp, %s', data)
    if response.status_code == 200:
        trade_status = data['status']
        trade_no = data['out_trade_no']
        total_fee = float(data['amount'])
        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee,
        }
        if trade_status == 'SUCCESS':
            check_channel_order(pay_id, total_fee, app_id)
            _LOGGER.info('zhongchengpay query order success, mch_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            add_pay_success(pay_order.mch_id, pay_id, total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
        else:
            _LOGGER.info(
                'zhongchengpay query order success but not pay success, trade_status:%s' % (
                    trade_status))
    else:
        _LOGGER.warn('zhongchengpay query order error, status_code: %s', response.status_code)
